package com.wk.springboot.config;

import com.wk.springboot.util.FileUtil;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * @Classname FileConfig
 * @Description TODO
 * @Date 2019/12/3 16:42
 * @Author by weikai
 */
//@Component
public class FileConfig implements CommandLineRunner {

  @Value("${source.file}")
  private String sourceFilePath;

  @Value("${target.file}")
  private String targetFilePath;

  @Override
  public void run(String... strings) throws Exception {
    System.out.println("================开始了");
    copeFile();
  }

  private void copeFile(){
    System.out.println("源文件路径："+sourceFilePath);
    System.out.println("目标文件路径："+targetFilePath);
    File sourceFile = new File(sourceFilePath);
    File targetFile = new File(targetFilePath);

    FileChannel outputFileChannel = null;
    FileLock outputFileLock = null;
    FileChannel inputFileChannel = null;

    try {
      RandomAccessFile outputRandomAccessFile = new RandomAccessFile(targetFile,"rw");
      RandomAccessFile inputRandomAccessFile = new RandomAccessFile(sourceFile,"r");
      outputFileChannel = outputRandomAccessFile.getChannel();
      inputFileChannel = inputRandomAccessFile.getChannel();
      outputFileLock = outputFileChannel.tryLock();
      if (outputFileLock.isValid()) {
        System.out.println("文件加锁成功"+targetFile.getAbsolutePath());
      }
      Long start = System.currentTimeMillis();
      System.out.println("============开始传输");
      FileUtil.copyFile(sourceFile,targetFile,inputFileChannel,outputFileChannel,true);
      Long end =  System.currentTimeMillis();
      System.out.println("============结束传输"+(end-start));
    } catch (FileNotFoundException e) {
      System.out.println("获取文件权限失败"+e);
    } catch (IOException e){
      System.out.println("获取文件锁失败"+e);
    }catch (Exception e){
      System.out.println("线程中断");
    }finally {
      try {
        if (outputFileLock != null) {
          outputFileLock.release();
        }
        if (outputFileChannel != null) {
          outputFileChannel.close();
        }
        if (inputFileChannel != null) {
          inputFileChannel.close();
        }
        System.out.println("文件释放锁成功");
      } catch (Exception e) {
        System.out.println("文件锁释放失败【{}】"+targetFile.getAbsolutePath());
      }
    }
  }
}
